using UnityEngine;
using System.Collections;

public class SmoothFollow : MonoBehaviour
{
		public float dampTime = 0.15f;
		public Transform target;
		private float minSizeY = 60f;
		public Vector3 velocity = Vector3.zero;

		// Update is called once per frame
		void Update ()
		{
				Vector3 final = Vector3.zero;// (GameController.jogadores[0].transform.position + GameController.jogadores[1].transform.position)/2;
				for (int x = 0; x < GameController.jogadores.Length; x++) {
						GameObject j = GameController.jogadores [x];
						if (j == null) {
								continue; 
						}
						if (final == Vector3.zero)
								final = j.transform.position;
						else
								final += j.transform.position;
			
				}
				final = final / GameController.numeroJogadores;

				Vector3 point = camera.WorldToViewportPoint (final);
				Vector3 delta = final - camera.ViewportToWorldPoint (new Vector3 (0.5f, 0.5f, point.z)); //(new Vector3(0.5, 0.5, point.z));
				Vector3 destination = transform.position + delta;
				transform.position = Vector3.SmoothDamp (transform.position, destination, ref velocity, dampTime);
				SetCameraSize ();
		}

		void SetCameraSize ()
		{
				//horizontal size is based on actual screen ratio
				float minSizeX = minSizeY * Screen.width / Screen.height;
				GameObject negoAEsquerda = null;
				GameObject negoADireita = null;
				for (int x = 0; x < GameController.numeroJogadores; x++) {
						GameObject jogador = GameController.jogadores [x];
						if (jogador == null || jogador.GetComponent<Jogador>().vivo == false)
								continue;
						if (negoAEsquerda == null || jogador.transform.position.x < negoAEsquerda.transform.position.x) {
								negoAEsquerda = jogador;
						}
						if (negoADireita == null || jogador.transform.position.x > negoADireita.transform.position.x) {
								negoADireita = jogador;
						}
						//Debug.Log ("ESQ : " + negoAEsquerda);
						//Debug.Log ("DIR :" + negoADireita);
				}

				//multiplying by 0.5, because the ortographicSize is actually half the height
				float width = Mathf.Abs ((negoAEsquerda.transform.position.x - negoADireita.transform.position.x - 130)) * 0.5f;
				float height = Mathf.Abs (negoAEsquerda.transform.position.y - negoADireita.transform.position.y) * 0.5f;
		
				//computing the size
				float camSizeX = Mathf.Max (width, minSizeX);
				camSizeX = 
				camera.orthographicSize = Mathf.Max (height,
		                                    camSizeX * Screen.height / Screen.width, minSizeY);
		}
	
	
}
